package cn.csg.iotplatform.module.system.controller.admin.templates;

import cn.csg.iotplatform.framework.common.exception.ServiceException;
import cn.csg.iotplatform.framework.common.exception.enums.GlobalErrorCodeConstants;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

@Tag(name = "管理后台 - 文件模板")
@RestController
@RequestMapping("/system/file-template")
@Slf4j
public class FileTemplateController {

    private static final String TEMPLATE_PATH = "templates/";

    @GetMapping("/download")
    @ResponseBody
    @PermitAll
    @Parameter(name = "fileName", description = "文件名", required = true, example = "用户导入模版.xlsx")
    public void download(@RequestParam("fileName") String fileName, HttpServletResponse response) {
        try {
            InputStream input = ResourceUtils.getURL("classpath:" + TEMPLATE_PATH + fileName).openStream();
            response.reset();
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            byte[] b = new byte[1024];
            int len;
            while ((len = input.read(b)) > 0) {
                response.getOutputStream().write(b, 0, len);
            }
            input.close();
        } catch (IOException e) {
            log.error("下载模板异常", e);
            throw new ServiceException(GlobalErrorCodeConstants.COMMON_DOWNLOAD_TEMPLATE);
        }
    }


}
